package gov.gfbzb.advice.config;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.splitter.DocumentBySentenceSplitter;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Log4j2
@Configuration
public class DocumentEmbeddingConfig {

    // 存储文档路径
    @Value("${rag.document-path}")
    private String documentPath;

    // 嵌入存储对象，用于存储文本片段及其向量表示
    public static final EmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();

    /**
     * 加载文档————项目启动时执行
     */
    @PostConstruct
    public CompletableFuture<Void> loadDocument() {
        try {
            if (documentPath == null || documentPath.isEmpty()) {
                log.error("文档路径为空，无法加载文档");
            }
            // 1. 从指定路径加载文档
            List<Document> documents = FileSystemDocumentLoader.loadDocuments(documentPath);

            if (documents == null || documents.isEmpty()) {
                log.warn("未加载到任何文档，路径: {}", documentPath);
            }

            log.info("成功加载 {} 个文档", documents.size());

            // 2. 按句子分块，每块最多2000字符，重叠20字符
            DocumentSplitter splitter = new DocumentBySentenceSplitter(2000, 20);

            // 3. 构建一个嵌入存储摄入器，配置文档分割器和嵌入存储
            EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()
                    .documentSplitter(splitter)
                    .embeddingStore(embeddingStore)
                    .build();

            // 4. 执行摄入操作，将文档分块、向量化并存储
            ingestor.ingest(documents);

        } catch (Exception e) {
            log.error("处理文档时发生未知异常", e);
            return CompletableFuture.failedFuture(e);
        }
        log.info("文档已成功处理完毕");
        return CompletableFuture.completedFuture(null);
    }
}
